import request from '../utils/request';
import { type SchoolItem, type SchoolParams } from '../types/school';
import { type ApiResponse } from '../types/auth';
import { stringify } from 'querystring';

/**
 * 获取学校列表
 * @param params 查询参数
 * @returns 学校列表
 */
export const getSchoolList = (params?: SchoolParams): Promise<{ list: SchoolItem[] }> => {
    return request.get('/schools/list', { params });
};

/**
 * 查询学校列表
 * @param params 查询参数
 * @returns 学校列表
 */
export const searchSchoolsList = (params: { manufacturer_id?: number, name?: string, status?: number }): Promise<{ schools: SchoolItem[] }> => {
    const validParams = Object.entries(params).reduce((acc, [key, value]) => {
        if (value !== undefined && value !== null && value !== '') {
            acc[key] = value;
        }
        return acc;
    }, {} as Record<string, string | number>);

    // 拼接查询字符串（如果有参数）
    const queryString = Object.keys(validParams).length > 0
        ? `?${stringify(validParams)}`
        : '';

    // 发送带参数的GET请求
    return request.get(`/schools/search${queryString}`);
};


/**
 * 获取学校详情
 * @param id 学校ID
 * @returns 学校详情
 */
export const getSchoolDetail = (id: number): Promise<SchoolItem> => {
    return request.get(`/schools/${id}`);
};

/**
 * 添加学校
 * @param data 学校信息
 * @returns 操作结果
 */
export const addSchool = (data: Omit<SchoolItem, 'id' | 'created_at' | 'updated_at'>) => {
    return request.post<ApiResponse<{ id: number }>>('/schools/created', data);
};

/**
 * 更新学校
 * @param id 学校ID
 * @param data 学校信息
 * @returns 操作结果
 */
export const updateSchool = (data: Omit<SchoolItem, 'createdAt' | 'updatedAt'>) => {
    return request.put<ApiResponse<{ success: boolean }>>(`/schools/${data.id}`, data);
};

/**
 * 删除学校
 * @param id 学校ID
 * @returns 操作结果
 */
export const deleteSchool = (id: number) => {
    return request.delete<ApiResponse<{ success: boolean }>>(`/schools/${id}`);
};